package cn.dubnation.base.commons;

import cn.dubnation.base.enums.ResponseCode;
import cn.dubnation.base.exception.BusinessException;
import cn.dubnation.base.util.AjaxResult;
import cn.dubnation.base.util.fastdfs.FastdfsUtil;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;


@RestController
@RequestMapping("/fastdfs")
public class FastDfsController {

    @Value("${fastdfs.storage}")
    private String prefixPath;

    /**
     * 上传图片
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("file") MultipartFile file) {
        String filename = file.getOriginalFilename();
        String extName = FilenameUtils.getExtension(filename);
        String uploadDfsPath = null;
        try {
            //上传文件并获取文件存储路径
            uploadDfsPath = FastdfsUtil.upload(file.getBytes(), extName);
            //TODO 文件上传方法有问题
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseCode.RESPONSE_CODE_4000013);
        }
        return AjaxResult.me().setCode(ResponseCode.RESPONSE_CODE_4000012.getCode())
                .setMessage(ResponseCode.RESPONSE_CODE_4000012.getMessage())
                .setData(prefixPath + uploadDfsPath);
    }
}
